package by.doubleyou.monitor.db;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.NamingException;
import javax.sql.ConnectionPoolDataSource;

import by.doubleyou.core.db.Storage;

public class LoggingStorage {

	private static String dbName = "w-store";
	private static String tableName = "LOG";

	private static String driver = "org.apache.derby.jdbc.ClientDriver";

	private String createString = "CREATE TABLE LOG  "
			+ "(TID INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
			+ " IP VARCHAR(10), TIME VARCHAR(40), ID VARCHAR(40))";

	// private String connectionURL = "jdbc:derby://localhost:1527/" + dbName +
	// ";create=true";

	private String prepareStaementString = "INSERT into LOG (IP, TIME, ID) values (?,?,?)";

	private static Storage st;

	private PreparedStatement statement;

	/*
	 * initialization
	 */
	protected void initialize() {
		try {
			// load embedded db
			Storage.load(driver);
			//org.osjava.sj.SimpleContextFactory.class;

			 
			// get storage
			st = Storage.getStorage(getDataSource());

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public LoggingStorage() {
		// register 
		initialize();
		
		// create if there is no such a table
		try {
			if (!st.isTableExist(tableName)) {
				Statement statementTMP = null;
				Connection conn = null;
				try {
					conn = st.getConnection();
					statementTMP = conn.createStatement();
					statementTMP.execute(createString);
				} finally {
					if (statementTMP != null)
						statementTMP.close();
					if (conn != null)
						st.closeSafe(conn);
				}
			}
			//prepare statement
			statement = st.getConnection().prepareStatement(
					prepareStaementString);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * get data source
	 * 
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("serial")
	public static ConnectionPoolDataSource getDataSource() throws SQLException {

		return new org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource() {
			{
				this.setDatabaseName(dbName);
				this.setCreateDatabase("create");
				this.setLogWriter(new PrintWriter(System.out));

			}
			@Override
			public String toString() {			
				return "DataSource [" + this.getDatabaseName() +  "]";
			}

		};

	}

	/**
	 * insert Data
	 * 
	 * @param ip
	 * @param time
	 * @param id
	 *            resource ip
	 * @throws SQLException
	 */
	public void insertData(String ip, String time, String id)
			throws SQLException {
		statement.setString(1, ip);
		statement.setString(2, time);
		statement.setString(3, id);
		statement.executeUpdate();
		System.out.println("[db]" + ip + ", " +time + ", "+ id);
	}
	
	/**
	 * close
	 * @throws SQLException
	 */
	public void close() throws SQLException {
		 st.closeSafe(statement.getConnection());
		 st.dispose();
	}

	public static void main(String[] args) throws Exception {
		new LoggingStorage().insertData("127.0.0.1", "1231231231", "1231");
	}
}
